<?php
require_once(dirname(__FILE__).'/../includes/db.inc.php');
class database
{
  // ==================================================================
  // Connect to the server and select initial database.
  function connect()
  {
    global $db;
    $this->conn = mysql_connect($db['server'], $db['username'], $db['password']);
    if (!$this->conn) {
      echo "<p>MySQL Error #" . mysql_errno() . "</b></p>n<p>" . mysql_error() . "</p>n";
    } //!$this->conn
    $this->selectdb($db['name']);
    mysql_query('SET NAMES utf8');
  }
  // ==================================================================
  // Connect to the server and select initial database.
  function selectDB($dbname)
  {
    if (!mysql_select_db($dbname, $this->conn)) {
      echo "<p>MySQL Error #" . mysql_errno() . "</b></p>n<p>" . mysql_error() . "</p>n";
    } //!mysql_select_db($dbname, $this->conn)
  }
  function startTransaction(){
    mysql_query("BEGIN;", $this->conn);
  }

  function commitTransaction(){
    mysql_query("COMMIT;", $this->conn);
  }

  function rollbackTransaction(){
    mysql_query("ROLLBACK;", $this->conn);
  }
  // ==================================================================
  // Main query function.
  function query($query)
  {
    //$query = $this->mySQLSafe($query);        
    $result = mysql_query($query);
        
    if (!$result) {
      return false;
    } //!$result
    else {
      return $result;
    }
  }
        function selectFirst($query, $maxRows = 0, $pageNum = 0)
        {
                $results = $this->select($query, $maxRows, $pageNum);
                if(!$results)
                {       
                        return $results;
                }
                return $results[0];
        }
  function select($query, $maxRows = 0, $pageNum = 0)
  {
    $this->query = $query;
    // start limit if $maxRows is greater than 0
    if ($maxRows > 0) {
      $startRow = $pageNum * $maxRows;
      $query    = sprintf("%s LIMIT %d, %d", $query, $startRow, $maxRows);
    } //$maxRows > 0
    $result = mysql_query($query, $this->conn);
    if ($this->error())
      die($this->debug());
    $output = false;
    for ($n = 0; $n < mysql_num_rows($result); $n++) {
      $row        = mysql_fetch_array($result);
      $output[$n] = $row;
    } //$n = 0; $n < mysql_num_rows($result); $n++
    return $output;
  } // end select
  // ==================================================================
  // Insert new row into database.
  function insert($table, $fields, $values)
  {
    $insert = $this->query("INSERT INTO $table ($fields) VALUES ($values)");
    return $insert;
  }
  // ==================================================================
  // Update row.        
  function update($table, $params, $condition)
  {
        //$sql = "UPDATE $table SET $param WHERE $condition"; 
    $update = $this->query("UPDATE $table SET $params WHERE $condition");
    return $update;
  }
  // ==================================================================
  // Delete an entry. 
  function delete($table, $condition){
    $this->query("DELETE FROM $table WHERE $condition");
  }
  
	function insert_array($table, $data){
		foreach ($data as $field => $value) {
			$fields[] = '`' . $field . '`';
      	$values[] = "'" . @mysql_real_escape_string($value) . "'";
    	} //$data as $field => $value
    	
    	$field_list = join(',', $fields);
    	$value_list = join(', ', $values);
    	$query      = "INSERT INTO `" . $table . "` (" . $field_list . ") VALUES (" . $value_list . ")";
    	$insert     = $this->query($query);
    	return $query;
    }
  
  function update_array($tablename, $record, $where)
  {
    $count  = 0;
    // don't need this any more, as we are escaping all user supplied content.
    //$record = str_replace("'", '', $record);
    foreach ($record as $key => $val) {
      if (is_numeric($val) == true) {
        $val = $val;
      } //is_numeric($val) == true
      else {
        $val = "'" . $val . "'";
      }
      if ($count == 0)
        $set = "" . $key . "" . "=" . $val;
      else
        $set .= ", " . "" . $key . "" . "= " . $val;
      $count++;
    } //$record as $key => $val
    $query       = "UPDATE " . $tablename . " SET " . $set . " WHERE " . $where;
    //echo $query;
    $this->query = $query;
    //echo $query;
    return mysql_query($query);
  } // end update
  function debug($type = "", $action = "", $tablename = "")
  {
    switch ($type) {
      case "connect":
        $message = "MySQL Error Occured";
        $result  = mysql_errno() . ": " . mysql_error();
        $query   = "";
        $output  = "Could not connect to the database. Be sure to check that your database connection settings are correct and that the MySQL server in running.";
        break;
      case "array":
        $message = $action . " Error Occured";
        $result  = "Could not update " . $tablename . " as variable supplied must be an array.";
        $query   = "";
        $output  = "Sorry an error has occured accessing the database. Be sure to check that your database connection settings are correct and that the MySQL server in running.";
        break;
      default:
        if (mysql_errno($this->conn)) {
          $message = "MySQL Error Occured";
          $result  = mysql_errno($this->conn) . ": " . mysql_error($this->conn);
          $output  = "Sorry an error has occured accessing the database. Be sure to check that your database connection settings are correct and that the MySQL server in running.";
        } //mysql_errno($this->conn)
        else {
          $message = "MySQL Query Executed Succesfully.";
          $result  = mysql_affected_rows($this->conn) . " Rows Affected";
          $output  = "view logs for details";
        }
        $linebreaks = array(
          "\n",
          "\r"
        );
        if ($this->query != "")
          $query = "QUERY = " . str_replace($linebreaks, " ", $this->query);
        else
          $query = "";
        break;
    } //$type
    $output = "<b style='font-family: Arial, Helvetica, sans-serif; color: #0B70CE;'>" . $message . "</b><br />\n<span style='font-family: Arial, Helvetica, sans-serif; color: #000000;'>" . $result . "</span><br />\n<p style='Courier New, Courier, mono; border: 1px dashed #666666; padding: 10px; color: #000000;'>" . $query . "</p>\n";
    return $output;
  }
  function error()
  {
    if (mysql_errno($this->conn))
      return true;
    else
      return false;
  }
  function insertid()
  {
    return mysql_insert_id($this->conn);
  }
  function affected()
  {
    return mysql_affected_rows($this->conn);
  }
  function close() // close conection
  {
    mysql_close($this->conn);
  }
  function blocker($user, $level, $time, $login, $loc)
  {
    global $glob;
    $expireTime = time() - ($time * 5);
    $this->delete($glob['dbprefix'] . "CubeCart_blocker", "lastTime<" . $expireTime);
    $query     = "SELECT * FROM " . $glob['dbprefix'] . "CubeCart_blocker WHERE `browser` = " . $this->mySQLSafe($_SERVER['HTTP_USER_AGENT']) . " AND `ip` = " . $this->mySQLSafe($_SERVER['REMOTE_ADDR']) . " AND `loc`= '" . $loc . "'";
    $blackList = $this->select($query);
    if ($blackList == TRUE && $blackList[0]['blockTime'] > time()) {
      // do nothing the user is still banned
      return TRUE;
    } //$blackList == TRUE && $blackList[0]['blockTime'] > time()
    elseif ($blackList == TRUE && $blackList[0]['blockTime'] > 0 && $blackList[0]['blockTime'] < time() && $blackList[0]['blockLevel'] == $level) {
      // delete the db row as user is no longer banned
      $this->delete($glob['dbprefix'] . "CubeCart_blocker", "id=" . $blackList[0]['id']);
      return FALSE;
    } //$blackList == TRUE && $blackList[0]['blockTime'] > 0 && $blackList[0]['blockTime'] < time() && $blackList[0]['blockLevel'] == $level
      elseif ($blackList == TRUE && $login == FALSE && $blackList[0]['blockTime'] == 0) {
      $newdata['lastTime'] = time();
      // If last attempt was more than the time limit ago we need to set the level to one
      // This stops a consecutive fail weeks later blocking on first attempt
      $timeAgo             = time() - $time;
      if ($blackList[0]['lastTime'] < $timeAgo) {
        $newdata['blockLevel'] = 1;
      } //$blackList[0]['lastTime'] < $timeAgo
      else {
        $newdata['blockLevel'] = $blackList[0]['blockLevel'] + 1;
      }
      if ($newdata['blockLevel'] == $level) {
        $newdata['blockTime'] = time() + $time;
        $this->update($glob['dbprefix'] . "CubeCart_blocker", $newdata, "id=" . $blackList[0]['id'], $stripQuotes = "");
        return TRUE;
      } //$newdata['blockLevel'] == $level
      else {
        $newdata['blockTime'] = 0;
        $this->update($glob['dbprefix'] . "CubeCart_blocker", $newdata, "id=" . $blackList[0]['id'], $stripQuotes = "");
        return FALSE;
      }
    } //$blackList == TRUE && $login == FALSE && $blackList[0]['blockTime'] == 0
      elseif ($blackList == FALSE && $login == FALSE) {
      // insert
      $newdata['blockLevel'] = 1;
      $newdata['blockTime']  = 0;
      $newdata['browser']    = $this->mySQLSafe($_SERVER['HTTP_USER_AGENT']);
      $newdata['ip']         = $this->mySQLSafe($_SERVER['REMOTE_ADDR']);
      $newdata['username']   = $this->mySQLSafe($user);
      $newdata['loc']        = "'" . $loc . "'";
      $newdata['lastTime']   = time();
      $this->insert($glob['dbprefix'] . "CubeCart_blocker", $newdata);
      return FALSE;
    } //$blackList == FALSE && $login == FALSE
  }
  function out($value)
  {
    echo $value . "<br/>";
  }
  function mySQLSafe($value, $quote = "'")
  {
    $this->out($value);
    // strip quotes if already in
    $value = str_replace(array(
      "\'",
      "'"
    ), "&#39;", $value);
    // Stripslashes 
    if (get_magic_quotes_gpc()) {
      $value = $value;
    } //get_magic_quotes_gpc()
    // Quote value
    if (version_compare(phpversion(), "4.3.0") == "-1") {
      $value = mysql_escape_string($value);
    } //version_compare(phpversion(), "4.3.0") == "-1"
    else {
      $value = mysql_real_escape_string($value);
    }
    $value = $quote . trim($value) . $quote;
    $this->out($value);
    return $value;
  }
  function numrows($query)
  {
    $this->query = $query;
    $result      = mysql_query($query, $this->conn);
    return mysql_num_rows($result);
  }


  // End of Class
  // ==================================================================

}
$database = new database();
$database->connect();
require_once "upgrade.php";
?>
